package com.wang.dao.impl;

import com.wang.dao.IAccountDao;
import com.wang.pojo.Account;
import com.wang.util.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by wangq on 2021/7/11.
 */
public class AccountDaoImpl implements IAccountDao {
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public Account findAccountByCardNo(String cardNo) throws SQLException {
//        DruidDataSource dataSource = DataSourceUtil.getInstance();
//        Connection connection = dataSource.getConnection();

        // 从当前线程中获取绑定的connection链接
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "SELECT * FROM account WHERE card_no = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, cardNo);
        preparedStatement.executeQuery();
        ResultSet resultSet = preparedStatement.getResultSet();

        Account account = new Account();
        while (resultSet.next()) {
            account.setCardNo(resultSet.getString("card_no"));
            account.setUserName(resultSet.getString("user_name"));
            account.setMoney(resultSet.getDouble("money"));
        }
        resultSet.close();
        preparedStatement.close();
//        connection.close(); 不要关闭当前线程中的链接
        return account;
    }

    @Override
    public void updateAccountMoneyByCardNo(Account account) throws SQLException {
//        DruidDataSource dataSource = DataSourceUtil.getInstance();
//        Connection connection = dataSource.getConnection();

        // 从当前线程中获取绑定的connection链接
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "UPDATE account SET money =? WHERE card_no = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1, account.getMoney());
        preparedStatement.setObject(2, account.getCardNo());
        preparedStatement.executeUpdate();
        preparedStatement.close();
//        connection.close(); 不要关闭当前线程中的链接
    }
}
